#include "CourseClient.h"
#include "coursecard_.h"
#include <QListWidget>
#include <QListWidgetItem>
#include <QNetworkRequest>
#include <QHttpMultiPart>
#include <QJsonDocument>
#include <QJsonArray>
#include <QDateTime>
#include <QNetworkReply>
#include <QJsonObject>

CourseClient::CourseClient(QWidget *parent)
    : QMainWindow(parent)
{
    resize(380, 600);
    m_list = new QListWidget;
    m_list->setFrameShape(QFrame::NoFrame);
    m_list->setSpacing(10);
    m_list->setContentsMargins(10, 10, 10, 10);
    setCentralWidget(m_list);

    fetch();
}

void CourseClient::fetch()
{
    QNetworkRequest req(QUrl("http://cs8.hyzyt.cn/vc/class/list"));
    QHttpMultiPart *multi = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    auto add = [multi](const char *k, const char *v) {
        QHttpPart p;
        p.setHeader(QNetworkRequest::ContentDispositionHeader,
                    QString("form-data; name=\"%1\"").arg(k));
        p.setBody(v);
        multi->append(p);
    };
    add("token",      "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxNywidXNlcl9pbmZvIjp7ImlkIjoxNywiYXBwX2lkIjoyLCJuYW1lIjoiXHU5MGRkXHU4MDAxXHU1ZTA4IiwiYXJlYV9jb2RlIjoiKzg2IiwicGhvbmUiOiIxODE2OTQ0NTY3OCIsInNleCI6MSwiYmlydGhkYXkiOjAsImlkX2NhcmQiOiIiLCJhdmF0YXIiOiIvdmNyL3NleF8xXzEuanBnIiwiY29sbGVnZSI6IiIsImdyYWRlIjoiIiwic3ViamVjdHMiOiIiLCJsZXZlbCI6MCwic3RhdHVzIjowLCJhZGRyZXNzIjoiIiwibGFzdF9sb2dpbl90aW1lIjoxNzQ5MjU4NTI1LCJjcmVhdGVfdGltZSI6MTc0MDExOTYyNywidGVtcF9jbGFzc19jb3VudCI6LTgxNywiaXNfc3VwZXJ2aXNlIjowLCJlcXVpcG1lbnRfaWQiOiJmZGEwNThiM2I1MzkwODdhOTQ0NzdkZjJlZjQ0ZGE4OCIsImlkZW50aXR5IjoidGVhY2hlciJ9LCJleHAiOjE3NTE4NzUxODN9.1MsEY_A7VOfge6_qIxfbGcsq4YBZ4bH5fOcLax1-l3M");
    add("app_id",     "2");
    add("page",       "1");
    add("per_page",   "10");
    add("type",       "0");
    add("state",      "-1");
    add("start_time", "1748707200");
    add("end_time",   "1751212800");
    add("lang",       "en-us");
    add("order",      "asc");

    QNetworkReply *reply = m_mgr.post(req, multi);
    reply->setParent(multi);   // 只需这一行即可
    multi->setParent(reply);   // 可以删掉
}

void CourseClient::onReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply) return;

    if (reply->error() == QNetworkReply::NoError) {
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
        QJsonArray arr = doc["data"]["list"].toArray();
        for (const QJsonValue &v : arr) {
            QJsonObject o = v.toObject();
            QString title = o["class_name"].toString();
            QString time  = QString("%1 ~ %2")
                               .arg(QDateTime::fromSecsSinceEpoch(o["class_start_time"].toInt())
                                        .toString("MM-dd hh:mm"))
                               .arg(QDateTime::fromSecsSinceEpoch(o["class_end_time"].toInt())
                                        .toString("hh:mm"));
            QString stu   = o["student_names"].toString();
            QString cover = o["payback_cover"].toString();
            int status    = o["status"].toInt();

            QListWidgetItem *item = new QListWidgetItem(m_list);
            item->setSizeHint(QSize(0, 120));
            m_list->setItemWidget(item, new CourseCard_(title, time, stu, cover, status, this));
        }
    } else {
        qWarning() << "HTTP error" << reply->errorString();
    }
    reply->deleteLater();
}
